import { arrayRemove } from '../utils/array'

let isActivation = false

const listener: Function[] = []

;(function () {
  window.addEventListener(
    'click',
    () => {
      isActivation = true
      listener.splice(0).forEach((fn) => fn())
    },
    { once: true }
  )
})()

export function useActivation<T>(cb: () => T, single?: AbortSignal): Promise<Awaited<T>> {
  return new Promise((resolve, reject) => {
    const run = async () => {
      try {
        const value = await cb()
        resolve(value)
      } catch (error) {
        reject(error)
      }
    }

    if (isActivation) {
      run()
    } else {
      listener.push(run)
      single?.addEventListener('abort', (event) => {
        arrayRemove(listener, (fn) => fn === run, true)
        reject((event.target as AbortSignal).reason)
      })
    }
  })
}
